import React from 'react';
import {
  Image,
  Text,
  TextInput,
  View,
  ScrollView,
  BackHandler,
  TouchableWithoutFeedback, Dimensions,
} from "react-native";
import ColorButton from 'react-native-cdy-baseui/components/ColorButton';
import HttpUtil from 'react-native-cdy-baseui/network/HttpUtil';
import ToastUtil from 'react-native-cdy-baseui/utils/ToastUtil';
import API from '../utils/API';
import AsyncStorage from '@react-native-community/async-storage';
import ModalViewUtil from 'react-native-cdy-baseui/utils/ModalViewUtil';
import PropTypes from 'prop-types';
import PlatformTouchable from 'react-native-platform-touchable';
import Colors from '../resources/Colors';
import Ionicons from 'react-native-vector-icons/Ionicons';
import Row from 'react-native-cdy-baseui/components/Row';
import {
  responsiveNumber,
} from 'react-native-responsive-number/src/index';

export default class LoginView extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: __DEV__? '15252118137' : '',
      password: __DEV__ ? '000000' : '',
      code: '',
      t: new Date().getTime(),
      secureTextEntry: true,
    };
  }

  async componentDidMount() {
    try {
      // const username = await AsyncStorage.getItem('USERNAME');
      // this.setState({username: username || ''});
    } catch (e) {}
  }

  login = async () => {
    try {
      const {data} = await HttpUtil.post(
        API.LOGIN_API,
        {
          userName: this.state.username,
          password: this.state.password,
          imgCode: this.state.code,
        },
        true,
      );

      HttpUtil.injectApi('token', config => {
        config.headers = {...config.headers, token: data.token};
        config.params = {
          ...config.params,
          token: data.token,
        };
      });
      HttpUtil.setUser(data);
      AsyncStorage.setItem('USER', JSON.stringify(data));

      ModalViewUtil.dismissBottomView();
      if (this.props.loginComplete) {
        this.props.loginComplete(data);
      }
    } catch (e) {
      ToastUtil.show(e.message);
      this.setState({t: new Date().getTime()});
    }
  };

  render() {
    const uri = HttpUtil.getBaseUrl() + API.IMAGE_CODE_API + this.state.t;
    console.log('uri:', uri);
    return (
      <View
        style={{
          width: Dimensions.get('screen').width * 0.5,
          height: Dimensions.get('screen').height * 0.4,
          backgroundColor: 'white',
          borderRadius: 5,
        }}>
        <Row
          style={{
            justifyContent: 'space-between',
            backgroundColor: 'white',
            marginTop: 15,
            marginHorizontal: 15,
          }}>
          <Text
            style={{
              color: Colors.primaryColor,
              fontSize: 14,
              fontWeight: 'bold',
            }}>
            登录
          </Text>
          <TouchableWithoutFeedback onPress={() => BackHandler.exitApp()}>
            <Ionicons
              name={'ios-close-circle-outline'}
              size={responsiveNumber(15 / 7)}
              color={Colors.primaryColor}
            />
          </TouchableWithoutFeedback>
        </Row>
        <ScrollView style={{flex: 1}} keyboardDismissMode="on-drag">
          <View
            style={{
              flex: 1,
              margin: 25,
              justifyContent: 'center',
            }}>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                height: 40,
                borderBottomWidth: 1,
                borderBottomColor: '#DFDFDF',
                marginTop: 5,
              }}>
              <Text>账号</Text>
              <TextInput
                placeholder={'请输入账号'}
                style={{marginLeft: 10, flex: 1}}
                value={this.state.username}
                ref={v => (this.phoneInput = v)}
                autoCorrect={false}
                autoCapitalize={'none'}
                onChangeText={text => this.setState({username: text})}
                onSubmitEditing={() =>
                  this.phoneInput && this.phoneInput.blur()
                }
              />
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                height: 40,
                borderBottomWidth: 1,
                borderBottomColor: '#DFDFDF',
                marginTop: 20,
              }}>
              <Text>密码</Text>
              <TextInput
                placeholder={'请输入密码'}
                ref={v => (this.passwordInput = v)}
                value={this.state.password}
                secureTextEntry={this.state.secureTextEntry}
                style={{marginLeft: 10, flex: 1}}
                onChangeText={text => this.setState({password: text})}
                onSubmitEditing={() =>
                  this.passwordInput && this.passwordInput.blur()
                }
              />
              <PlatformTouchable
                onPress={() =>
                  this.setState({
                    secureTextEntry: !this.state.secureTextEntry,
                  })
                }>
                <Ionicons
                  name={
                    this.state.secureTextEntry
                      ? 'eye-off-outline'
                      : 'eye-outline'
                  }
                  size={30}
                  color={Colors.primaryColor}
                />
              </PlatformTouchable>
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                height: 40,
                borderBottomWidth: 1,
                borderBottomColor: '#DFDFDF',
                marginTop: 20,
              }}>
              <Text>验证码</Text>
              <TextInput
                placeholder={'请输入验证码'}
                ref={v => (this.codeInput = v)}
                value={this.state.code}
                keyboardType={'number-pad'}
                style={{marginLeft: 10, flex: 1}}
                onChangeText={text => this.setState({code: text})}
                onSubmitEditing={() => this.login()}
              />
              <PlatformTouchable
                onPress={() => this.setState({t: new Date().getTime()})}>
                <Image
                  style={{
                    width: 120,
                    height: 40,
                    backgroundColor: 'gray',
                  }}
                  resizeMode={'contain'}
                  onError={({nativeEvent: {error}}) =>
                    ToastUtil.show('验证码加载失败')
                  }
                  source={{
                    uri: uri,
                  }}
                />
              </PlatformTouchable>
            </View>
          </View>
          <ColorButton
            onPress={this.login}
            backgroundColor={Colors.primaryBackgroundColor}
            containerStyle={{
              marginHorizontal: 15,
              marginBottom: 15,
            }}>
            登录
          </ColorButton>
        </ScrollView>
      </View>
    );
  }
}
LoginView.propTypes = {
  loginComplete: PropTypes.func,
};
